package top.yzhelp.enjoyinformation.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author <a href="https://github.com/gongsir0630">码之泪殇</a>
 * @date 2021/4/11 14:45
 * 你的指尖,拥有改变世界的力量
 * @description 通用公开接口
 */
@RestController
@Slf4j
@RequestMapping("public")
public class PublicController {

    @Value("${spring.application.name}")
    private String appName;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 从认证信息中获取用户Id: userId == openId
     * @return userId
     */
    private String getUserId() {
        Object principal = SecurityUtils.getSubject().getPrincipal();
        return principal != null ? principal.toString() : "visitor";
    }

    /**
     * 图片上传
     * @param file 图片文件
     * @return 图片 url 地址
     */
    @PostMapping(path = "/upload")
    public ResponseEntity<JSONObject> uploadFile(MultipartFile file) {
        Assert.notNull(file,"--->>>file 为空");
        String originalName = file.getOriginalFilename();
        String suffix = originalName != null ? originalName.substring(originalName.lastIndexOf(".")) : ".jpg";
        // 生成新的文件名
        String fileName = appName+"/"+getUserId()+"/"+ UUID.randomUUID().toString()+suffix;
        // 图片上传接口
        String uploadUrl = "https://yzhelp.top/public/upload";
//        String uploadUrl = "http://localhost:8082/public/upload";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
        params.add("file",file.getResource());
        params.add("key",fileName);
        HttpEntity<MultiValueMap<String,Object>> httpEntity = new HttpEntity<>(params,headers);
        return restTemplate.postForEntity(uploadUrl, httpEntity, JSONObject.class);
    }
}
